package com.jsoup.controller;

import com.jsoup.bean.User;
import com.jsoup.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RegisterController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "register";
    }

    /**
     * 注册
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Object register(User user) {

        Map<Object, Object> map = new HashMap<>();
        user.setUserLevelId(2);
        user.setUserRegistrationTime(new Timestamp(System.currentTimeMillis()));
        Md5Hash md5UserPassword = new Md5Hash(user.getUserPassword(), ByteSource.Util.bytes(user.getUserName()), 1024);
        user.setUserPassword(md5UserPassword.toString());
        int count = userService.insertSelective(user);
        if (count > 0) {
            map.put("result", "success");
        }
        return map;
    }

    /**
     * 判断用户名、邮箱是否已注册
     *
     * @param userName
     * @return
     */
    @RequestMapping("/checkUserOnly")
    @ResponseBody
    public Object checkUserOnly(@RequestParam(value = "userName") String userName, @RequestParam(value = "userEmail") String userEmail) {
        Map<Object, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        if (userName != null) {
            User user = new User();
            user.setUserName(userName);
            User result = userService.getUser(user);
            if (result != null) {
                i += 1;
            }
        }
        if (userEmail != null) {
            User user = new User();
            user.setUserEmail(userEmail);
            User result = userService.getUser(user);
            if (result != null) {
                j += 1;
            }
        }
        if (i > 0 && j == 0) {
            map.put("result", "该用户名已经被注册");
        }
        if (i == 0 && j > 0) {
            map.put("result", "该邮箱已经被注册");
        }
        if (i > 0 && j > 0) {
            map.put("result", "该用户名、邮箱都已经被注册");
        }
        return map;
    }

}
